#include "SkyPlotWidget.h"
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <math.h>
#include <QDebug>

SkyPlotWidget::SkyPlotWidget(QWidget *parent) :
    QWidget(parent)
{
}

SkyPlotWidget::~SkyPlotWidget()
{
}

void SkyPlotWidget::paintEvent(QPaintEvent *)
{
    QPainter pt(this);
    int fontSize = pt.font().pixelSize() == -1 ? pt.font().pointSize()
                                               : pt.font().pixelSize();
    float size = (width() > height() ? height() : width()) - 40;
    float leftBorder = size * -0.5;
    float rightBorder = size * 0.5;

    pt.translate(width() / 2, height() / 2);
    QPen pen(Qt::SolidLine);
    pen.setColor(Qt::black);
    pen.setWidth(2);
    pt.setPen(pen);

    pt.setBrush(Qt::white);
    pt.drawEllipse(QPointF(0, 0), rightBorder, rightBorder);

    pen.setWidth(1);
    pen.setStyle(Qt::DotLine);
    pt.setPen(pen);
    pt.drawEllipse(QPointF(0, 0), size / 4, size / 4);

    pt.drawLine(leftBorder, 0, rightBorder, 0);
    pt.drawLine(0, leftBorder, 0, rightBorder);

    pt.drawText(QPoint(0, 0), "90");
    pt.drawText(QPoint(0, leftBorder / 2), "45");
    pt.drawText(QPoint(0, leftBorder), "0");
    foreach(const SatelliteInfo &s, _satList)
    {
        if(s.cNo == -1)
            continue;
        float r = rightBorder * (90 - s.angleOfElevation) / 90;
        float angle = 2 * 3.14159265 * (s.angleOfDirection - 90) / 360;
        float x = cosf(angle) * r;
        float y = sinf(angle) * r;
        int cr, cg, cb = 0;
        if(s.cNo < 10)
            cr = 255, cg = 64;
        else if(s.cNo < 20)
            cr = 128, cg = 128;
        else if(s.cNo < 30)
            cr = 64, cg = 128;
        else if(s.cNo <  40)
            cr = 64, cg = 255;
        else
            cr = 0, cg = 255;

        pt.setBrush(QColor(cr, cg, cb));
        pt.setPen(Qt::NoPen);
        pt.drawEllipse(QPoint(x, y), fontSize * 2, fontSize * 2);
        pt.setPen(Qt::black);
        pt.drawText(
            QRect(x - fontSize * 2, y - fontSize * 2, fontSize * 4, fontSize * 4),
            Qt::AlignHCenter | Qt::AlignVCenter,
            QString("%1%2").arg(_prefix).arg(s.satId));
        //qDebug()<<s.satId<<s.angleOfDirection<<s.angleOfElevation<<x<<y;
    }
}

void SkyPlotWidget::setSatellites(const QList<SatelliteInfo> &sats)
{
    _satList = sats;
    update();
}
